package com.yutou.droid.UselessCode.Utils;

import android.app.Application;
import android.content.ComponentName;
import android.content.Intent;

import com.yutou.droid.ProxyActivity;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * 动态代理，尝试欺骗掉Android的Activity验证
 */
public class ProxyClass implements InvocationHandler {
    private Object data;
    private Application application;
    public ProxyClass(Object data, Application application) {
        // TODO Auto-generated constructor stub
        this.data = data;
        this.application=application;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) {
        // TODO Auto-generated method stub
        Object object=null;
        try {
            if(method.getName().equals("startActivity")){
                Intent intent = null,proxyIntent;
                int index=-1;
                //拿到原本（未注册Activity）的Intent
                for (int i = 0; i < args.length; i++) {
                    if (args[i] instanceof Intent) {
                        intent= (Intent) args[i];
                        index=i;
                        break;
                    }
                }
                System.out.println("当前触发方法："+method.getName()+" 包名："+intent.getComponent().getClassName());
                //替换掉Intent
                proxyIntent=new Intent();
                ComponentName componentName=new ComponentName(application, ProxyActivity.class); //替换成代理Activity
                proxyIntent.setComponent(componentName);
                proxyIntent.putExtra("oldIntent",intent);
                args[index]=proxyIntent; //偷梁换柱
            }

            object= method.invoke(data, args);

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("替换失败");
        }
        return object;
    }

}
